<template>
  <a
    v-if="!openInNew"
    class="custom-link"
    :href="props.href"
    :target="props.target"
    :rel="props.rel"
    @click="handleClick">
    <slot></slot>
  </a>
  <button v-else class="custom-link" type="button" @click="openInNewTabOrWindow">
    <slot></slot>
  </button>
</template>

<script setup lang="ts">
const props = defineProps({
  href: {
    type: String,
    default: '#',
  },
  target: {
    type: String,
    default: '_self',
  },
  // 定义链接资源与当前文档的关系
  rel: {
    type: String,
    default: 'noopener noreferrer',
  },
  // 是否打开一个新的标签页
  openInNew: {
    type: Boolean,
    default: false,
  },
});
// 定义发射的事件
const emit = defineEmits(['click']);

// 点击事件处理函数
const handleClick = (event: MouseEvent) => {
  emit('click', event);
};

// 在新标签页或新窗口中打开链接的函数
const openInNewTabOrWindow = () => {
  const newWindow = window.open(props.href, props.target === '_blank' ? '_blank' : undefined);

  if (!newWindow) {
    console.warn('新窗口打开失败（可能被浏览器阻止了）');
  }
};
</script>

<style scoped lang="scss">
.custom-link {
  @apply text-[#4f858afe] text-sm cursor-pointer hover:underline underline-offset-4;
  transform: scale(0.5);
}
</style>
